import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {TodolistsService} from '../services/todolists.service';
import {TodoData} from '../models/todolists';
import {Router} from '@angular/router';
import {AuthService} from '../services/auth.service';

import {FilterType, OperationType} from './todolist-operates/todolist-operates.component'
import {User} from '../models/auth';
import {Subject} from 'rxjs';

@Component({
  selector: 'app-dashboard',
  standalone: false,
  templateUrl: './dashboard.component.html',
  styleUrl: './dashboard.component.css',
})

export class DashboardComponent implements OnInit {
  todolists: TodoData[] = [];
  filterDate: TodoData[] = []
  currentFilter: FilterType = 'all';
  userInfo: User = {
    id: '',
    username: '',
    email: ''
  }
  constructor(
    private TodolistsService: TodolistsService,
    private router: Router,
    private authService: AuthService
  ) { }
  ngOnInit() {
    this.authService.getUserInfo().subscribe({
      next: res => {
        if(res.data){
          this.userInfo = res.data.user
        }
      }
    })
    this.loadTodolists();
  }

  loadTodolists(): void {
    this.TodolistsService.getTodolists().subscribe({
      next: request => {
        if(request.code === 200 && request.data?.todos) {
          this.todolists = request.data?.todos
          // this.updateUnfinishedTodos()

          this.updateFilterDate(this.currentFilter);
          // console.log(this.todolists);
        }
      },
      error: (error) => {
        console.error('Failed to load todolists:', error);
      }
    })
  }

  onTodoAdded(): void {
    this.loadTodolists();
  }

  updateFilterDate(filterType?: FilterType): void{
    switch(filterType) {
      case 'active':
        this.filterDate = this.todolists.filter((item) => !item.completed);
        break;
      case 'completed':
        this.filterDate = this.todolists.filter((item) => item.completed);
        break;
      case 'all':
      default:
        this.filterDate = [...this.todolists];
        break;
    }
  }

  onFilterDate(filterType: FilterType): void{
    this.currentFilter = filterType;
    this.updateFilterDate(filterType);
  }

  onOperateAction(operation: OperationType): void {
    switch(operation) {
      case 'clearCompleted':
        this.clearCompletedTodos();
        break;
      case 'clearAll':
        this.clearAllTodos();
        break;
      case 'logout':
        this.logout();
        break;
    }
  }

  private clearCompletedTodos(): void {
    const completedTodosIds: string[] = [];
    this.todolists.forEach(item => {
      if (item.completed) {
        completedTodosIds.push(item._id)
      }
    })
    if (completedTodosIds.length) {
      this.TodolistsService.deleteTodoLists(completedTodosIds).subscribe({
        next: request => {
          this.loadTodolists();
        },
        error: (error) => {
          console.error('Failed to delete todolists:', error);
        }
      })
    }
  }

  private clearAllTodos(): void {
    if (this.todolists.length === 0) {
      return;
    }
    const AllTodosIds: string[] = [];
    this.todolists.forEach(item => {
      AllTodosIds.push(item._id);
    })
    this.TodolistsService.deleteTodoLists(AllTodosIds).subscribe({
      next: request => {
        this.loadTodolists();
      },
      error: (error) => {
        console.error('Failed to delete todolists:', error);
      }
    })
  }

  private logout(): void {
    this.authService.logout();
    this.router.navigate(['/login']);
  }

  onDeleteTodo(id: string): void {
    this.todolists = this.todolists.filter(item => item._id !== id)
    this.updateFilterDate(this.currentFilter); // 更新 filterDate 以保持一致性
  }

}
